package com.tul.exercise.base.innerclass;


import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;

/**
 * @ClassName Sequence
 * @Description 迭代器模式
 * @Author tul 2018/7/29
 * @Version 1.0
 **/
public class Sequence {

    /**
     * 对象数组
     */
    private Object[] items;

    /**
     * index
     */
    private int next = 0;

    /**
     * 构造
     * @param size 数组大小
     */
    public Sequence(int size) {
        items = new Object[size];
    }

    /**
     * add方法
     * @param x 对象
     */
    public void add(Object x) {
        if (next < items.length) {
            items[next++] = x;
        }
    }

    /**
     * 迭代器类
     */
    private class SequenceSelector implements Selector {
        private int i = 0;
        @Override
        public boolean end() {
            return i == items.length;
        }

        @Override
        public Object current() {
            return items[i];
        }

        @Override
        public void next() {
            if (i < items.length) {
                i++;
            }
        }
    }

    /**
     * 获取迭代器
     * @return 迭代器
     */
    public Selector selector() {
        return new SequenceSelector();
    }

    /**
     * toString 方法
     * @return 字符串
     */
    public String toString() {
        return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
    }
}
